package com.example.play.view


import android.view.View
import androidx.fragment.app.activityViewModels
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.example.base.app.RouterPath
import com.example.common.entity.CommendEntity
import com.example.common.entity.SimpleVideoEntity
import com.example.common.mvi.BaseMviFragment
import com.example.play.R
import com.example.play.adapter.CommentListAdapter
import com.example.play.databinding.FragmentCommentBinding
import com.example.play.intent.PlayViewIntent
import com.example.play.state.PlayUiState
import com.example.play.vm.PlayViewModel
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.flow.collectLatest

@Route(path = RouterPath.PATH_COMMENT_PAGE)
@AndroidEntryPoint
class CommentFragment : BaseMviFragment<FragmentCommentBinding>() {
    @Autowired
    @JvmField var itemId:String=""
    @Autowired
    @JvmField var moduleType:Int=0

    private val mViewModel: PlayViewModel by activityViewModels ()
    private lateinit var commentListAdapter: CommentListAdapter
    private val commendEntity= mutableListOf<CommendEntity>()

    override fun getLayoutId(): Int = R.layout.fragment_comment

    override fun initViews() {
        ARouter.getInstance().inject(this)
        commentListAdapter= CommentListAdapter(commendEntity)
        mDataBinding.rvComment.apply {
            layoutManager=LinearLayoutManager(requireContext(),LinearLayoutManager.VERTICAL,false)
            adapter=commentListAdapter
        }
    }

    override suspend fun sendViewIntent() {
        super.sendViewIntent()
        if (moduleType == 0){
            mViewModel.channel.send(PlayViewIntent.LoadVideoCommends(0,itemId))
        }else{
            mViewModel.channel.send(PlayViewIntent.LoadVideoCommends(1,itemId))
        }

    }

    override suspend fun collectUIState() {
        super.collectUIState()
        mViewModel.uiStateFlow.collectLatest {
            when(it){
                is PlayUiState.LoadVideoCommendsSuccess-> updateVideoCommends(it.list)
                else->{}
            }
        }
    }

    private fun updateVideoCommends(list: List<CommendEntity>) {
        commendEntity.clear()
        commendEntity.addAll(list)
        commentListAdapter.notifyDataSetChanged()
    }
}